package t2.server;

import org.apache.log4j.Logger;

import t2.client.rpc.SendData;
import t2.server.xbee.XBeePort;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.rapplogic.xbee.api.XBee;
import com.rapplogic.xbee.api.XBeeAddress16;
import com.rapplogic.xbee.api.XBeeAddress64;
import com.rapplogic.xbee.api.XBeeException;
import com.rapplogic.xbee.api.XBeeResponse;
import com.rapplogic.xbee.api.XBeeTimeoutException;
import com.rapplogic.xbee.api.zigbee.ZNetExplicitTxRequest;
import com.rapplogic.xbee.api.zigbee.ZNetTxRequest;
import com.rapplogic.xbee.api.zigbee.ZNetTxStatusResponse;
import com.rapplogic.xbee.util.DoubleByte;

public class SendDataImpl extends RemoteServiceServlet implements SendData {

    private static final Logger log = Logger.getLogger(SendDataImpl.class);
    private static final long serialVersionUID = -7085709052771787141L;

    @Override
    public String transmitExplicit(int frameId, int[] xbAddr64, int[] xbAddr16, int[] payload, int sourceEndpoint, int destEndpoint) {
        
        XBeeAddress64 addr64 = new XBeeAddress64(xbAddr64);
        XBeeAddress16 addr16 = new XBeeAddress16(xbAddr16);
        DoubleByte clusterId = new DoubleByte(0x0, ZNetExplicitTxRequest.ClusterId.SERIAL_LOOPBACK.getValue());

        XBee xbee = XBeePort.getXBeePort().getXbee();
        ZNetExplicitTxRequest request = new ZNetExplicitTxRequest(frameId, addr64, addr16, 
                ZNetTxRequest.DEFAULT_BROADCAST_RADIUS, ZNetTxRequest.Option.UNICAST, payload,
                sourceEndpoint, destEndpoint, clusterId, ZNetExplicitTxRequest.znetProfileId);

        try {
            log.info("sending explicit " + request.toString());
            xbee.sendAsynchronous(request);
            XBeeResponse response = xbee.getResponse();
            log.info("received response " + response.toString());
            return response.toString();
        }
        catch (XBeeException e) {
            return e.toString();
        }
    }

    @Override
    public String transmit(int[] xbAddr64, int[] payload){
        XBeeAddress64 addr64 = new XBeeAddress64(xbAddr64);
        ZNetTxRequest request = new ZNetTxRequest(addr64, payload);
        ZNetTxStatusResponse response = null;
        try {
            response = (ZNetTxStatusResponse) XBeePort.getXBeePort().getXbee().sendSynchronous(request, 10000);
        }
        catch (XBeeTimeoutException e) {
            e.printStackTrace();
        }
        catch (XBeeException e) {
            e.printStackTrace();
        }

        return response.toString();
    }
}